package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.User;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWork;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService iSeckillVoucherService;
    @Resource
    private RedisIdWork redisIdWork;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redissonClient;

    private ExecutorService executor = Executors.newSingleThreadExecutor();

    @PostConstruct
    public void init() {
        executor.execute(new VoucherOrderThread());
    }
    String queueName = "stream.orders";
    private class VoucherOrderThread implements Runnable {
        @Resource
        private VoucherOrderMapper voucherOrderMapper;
        @Override
        public void run() {
            while (true){
                try {
                    //1.获取消息队列中的订单 XREADGROUP GROUP g1 c1  COUNT 1 BLOCK 2000 STREAM stream.orders >
                    List<MapRecord<String, Object, Object>> read = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
                    );
                    //2.判断消息获取是否成功
                    if (read == null || read.isEmpty() ){
                        continue;
                    }
                    //2.1如果获取失败表示没有消息
                    MapRecord<String, Object, Object> entries = read.get(0);
                    Map<Object, Object> value = entries.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    //2.2如果成功则可以下单
                    voucherOrderMapper.insert(voucherOrder);
                    //ACK确认 SACK stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",entries.getId());

                }catch (Exception e){
                    //消息处理失败去pending-list中取出消息去处理
                    log.info("消息队列处理异常",e);
                    handPendingList();
                }
            }


        }

        private void handPendingList() {
            while (true) {
                try {
                    //1.获取pending-List中的订单 XREADGROUP GROUP g1 c1  COUNT 1 BLOCK 2000 STREAM stream.orders 0
                    List<MapRecord<String, Object, Object>> read = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create(queueName, ReadOffset.from("0"))
                    );
                    //2.判断消息获取是否成功
                    if (read == null || read.isEmpty()) {
                        break;
                    }
                    //2.1如果获取失败表示没有消息
                    MapRecord<String, Object, Object> entries = read.get(0);
                    Map<Object, Object> value = entries.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    //2.2如果成功则可以下单
                    voucherOrderMapper.insert(voucherOrder);
                    //ACK确认 SACK stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", entries.getId());

                } catch (Exception e) {
                    log.info("pending-List处理异常",e);
                }
            }
        }
    }

    private static final DefaultRedisScript<Long> SECKILL_KEY;
    static {
        SECKILL_KEY = new DefaultRedisScript<>();
        SECKILL_KEY.setScriptText("seckill.lua");
        SECKILL_KEY.setResultType(Long.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result seckillVoucher(Long voucherId) {
        //获取用户id
        Long userId = UserHolder.getUser().getId();
        long orderId = redisIdWork.nextId("order");
        //1.执行Lua脚本
        Long result = stringRedisTemplate.execute(SECKILL_KEY,
                Collections.EMPTY_LIST,
                voucherId.toString(),
                userId.toString(),
                String.valueOf(orderId)
        );
        //2.判断是否为0
        if (result != 0) {
            return Result.fail(result ==1 ? "库存为0":"重复下单");
        }
        //3.有购买资格，将订单放到用户队列中

    

        return Result.ok(orderId);
        //--------------------------
        //1.查询优惠券
//        SeckillVoucher seckillVoucher = iSeckillVoucherService.getById(voucherId);
//        //2.判断秒杀活动是否开始
//        if (seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())){
//           return Result.fail("活动尚未开始");
//        }
//        //3.判断秒杀活动是否已经过期
//        if (seckillVoucher.getEndTime().isBefore(LocalDateTime.now())){
//           return Result.fail("活动已结束");
//        }
//        //4.判断库存是否充足
//        Integer stock = seckillVoucher.getStock();
//        if (stock < 1){
//           return Result.fail("优惠券秒杀完毕");
//        }
//        SeckillVoucher newSeckillVoucher = new SeckillVoucher();
//        newSeckillVoucher.setStock(stock-1);
//        QueryWrapper queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("voucher_id", voucherId);
//        queryWrapper.gt("stock", 0);
//        boolean update = iSeckillVoucherService.update(newSeckillVoucher, queryWrapper);
//        if (!update){
//            return Result.fail("更新失败");
//        }
//
//        Long userId = UserHolder.getUser().getId();
//        //SimpleRedisLock redisLock = new SimpleRedisLock(stringRedisTemplate,userId+"");
//        RLock redisLock = redissonClient.getLock("lock:order" + userId);
//        Boolean lock = redisLock.tryLock();
//        if (!lock){
//            return Result.fail("不能重复抢购优惠券");
//        }
//        try{
//            //ISeckillVoucherService proxy = (ISeckillVoucherService)AopContext.currentProxy();
//            return createOrder(voucherId);
//        }finally {
//            redisLock.unlock();
//        }
    }

    public synchronized Result createOrder(long voucherId) {
        //6.创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        long id = redisIdWork.nextId("voucherOrder");
        voucherOrder.setId(id);
        Long userId = UserHolder.getUser().getId();
        //一人一单的判断
        QueryWrapper queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("user_id", userId);
        queryWrapper2.eq("voucher_id", voucherId);
        int count = this.count(queryWrapper2);
        if (count > 0){
            return Result.fail("不能重复抢购优惠券");
        }
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
        this.save(voucherOrder);
        return Result.ok(id);
    }
}
